package com.memo.model;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ImageSpan;
import android.widget.EditText;

import com.memo.Utils.ImageUtils;
import com.memo.Utils.ScreenUtils;

public class editmodel {
    Activity activity;
    EditText edit_activity_content;
    public editmodel(Activity activity, EditText edit_activity_content){
        this.activity=activity;
        this.edit_activity_content=edit_activity_content;
    }
    //region 插入图片
    public void insertImg(String path){
        edit_activity_content.append("\n");
        String tagPath = "<img src=\""+path+"\"/>";//为图片路径加上<img>标签
        Bitmap bitmap = BitmapFactory.decodeFile(path);
        if(bitmap != null){
            SpannableString ss = getBitmapMime(path,tagPath);
            insertPhotoToEditText(ss);
            edit_activity_content.append("\n");
        }
    }
    //endregion

    //region 将图片插入到EditText中
    private void insertPhotoToEditText(SpannableString ss){
        Editable et = edit_activity_content.getText();
        int start = edit_activity_content.getSelectionStart();
        et.insert(start,ss);
        edit_activity_content.setText(et);
        edit_activity_content.setSelection(start+ss.length());
        edit_activity_content.setFocusableInTouchMode(true);
        edit_activity_content.setFocusable(true);
    }

    private SpannableString getBitmapMime(String path,String tagPath) {
        SpannableString ss = new SpannableString(tagPath);//这里使用加了<img>标签的图片路径

        int width = ScreenUtils.getScreenWidth(activity);
        int height = ScreenUtils.getScreenHeight(activity);


        Bitmap bitmap = ImageUtils.getSmallBitmap(path,width,480);
        ImageSpan imageSpan = new ImageSpan(activity, bitmap);
        ss.setSpan(imageSpan, 0, tagPath.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return ss;
    }
}
